import time
import config
import datetime
import difflib
import obj_config
import setting_get_set


class Service_functions:
    def check_internet(self):
        import requests

        try:
            # requests.get("http://google.com")
            requests.get("https://yandex.ru")  # Хули Импортозамещение
            return True
        except requests.ConnectionError:
            return False

    def fuzz_word_cheek(self, len_words):
        if config.flexible_probability_cmd_cmds:
            par = 100 / len_words
            sum_par = par * config.count_error_word
            # print(sum_par,par,3333333333)
            if int(sum_par) < 100:
                if (100 - sum_par) >= config.probability_cmd_const:
                    config.probability_cmd = 100 - sum_par
                    # print(f"config.probability_cmd={config.probability_cmd}=111111")
                else:
                    # print("ffffffffffff")
                    config.probability_cmd = config.probability_cmd_const
        else:
            # print("жжжжжжжжжжжжжжжжжж")
            config.probability_cmd = config.probability_cmd_const

    def util_command_history_write(self, vosk_str: str, name: str) -> None:
        # запись в файл информации о выполненных функциях
        check_record = open(name, "a")
        check_record.write(vosk_str)
        check_record.close()

    def util_meta_data(self, func: str, file_name: str, tags: list = []) -> None:
        # Сбор о информации о выполненых командах и времени их исполнении
        if config.meta_data:
            if len(tags) != 0:
                str_tags = "".join(tags)
            else:
                str_tags = ""
            now = datetime.datetime.now()
            date_call_func = datetime.datetime(
                now.year, now.month, now.day, now.hour, now.minute
            )
            self.util_command_history_write(
                f"{func} {str_tags} {date_call_func}\n", f"{config.path_bd}{file_name}"
            )

    def util_find(self, str_source: str, str_find: str) -> bool:
        if str_source.find(str_find) != -1:
            return True
        else:
            return False

    def restart_modul(self):
        obj_config.obj_import_egg.settings()
        return "Модули переподключены"

    def json_renewal(self) -> str:
        # Дописать
        config.cmds = setting_get_set.read_config("config.json")
        config.settings = setting_get_set.read_config("settings.json")
        config.language = setting_get_set.read_config("language.json")
        return "Конфигурация ядра обновлена"

    def dec_queue_clear(self) -> None:
        if config.stream_speech.qsize() >= 10:
            config.stream_speech.queue.clear()

    def find_entry_all(self, a_str: str, sub: str):
        start = 0
        list_index = []
        list_len = []
        while True:
            start = a_str.find(sub, start)
            if start != -1:
                list_index.append(start)
                start = start + len(sub)
                list_len.append(start)
            if start == -1:
                break
        return list_index, list_len

    def search_parmas(self, func: str, sub: str) -> list:
        tags = []
        start = 0
        old = 0
        param = "params_"
        index_tags = func.find(param)
        params = func[index_tags + len(param) : len(func)]
        while True:
            start = params.find(sub, start)
            if start != -1:
                start = start + len(sub)
                tags.append(params[old : start - 1])
                old = start
            if start == -1:
                break
        return tags

    def search_entry_all(self, func: str, sub: str) -> list:
        tags = []
        start = 0
        old = 0
        params = func[0 : len(func)]
        while True:
            start = params.find(sub, start)
            if start != -1:
                start = start + len(sub)
                tags.append(params[old : start - 1])
                old = start
            if start == -1:
                break
        return tags

    def cheek_say(self, message: str) -> bool:
        if config.permission_check_speech:
            obj_config.communication_obj.messege(f"Вы имели виду '{message}'\n")
            cmd_str = obj_config.obj_api.queue_voice_time_str_api()
            value = obj_config.decoders_obj.dec_function_recognition_keys(
                cmd_str, "other"
            )

            if "yes" in value:
                return True
            elif "no" in value:
                return False
            else:
                return False
        else:
            return True

    def error_correction(
        self, input_str: str, dict_words, name_err: int = 1, cof_wer=0.7
    ) -> str:
        input_str = input_str.split(" ")
        list_str = []
        for str_i in input_str:
            exact_words = difflib.get_close_matches(
                str_i, dict_words, name_err, cof_wer
            )
            if len(exact_words) > 0:
                list_str.append(exact_words[0])
            else:
                list_str.append(str_i)

        return " ".join(list_str)

    def loop_func(self, func: str, time_aut=1, kol: int = 3, tags=[]) -> None:
        if len(tags) == 0:
            for x in range(0, kol):
                # Вызов функции
                time.sleep(time_aut)
                obj_config.service_functions_obj.call_function(func)
        else:
            for x in range(0, kol):
                # Вызов функции
                time.sleep(time_aut)
                obj_config.service_functions_obj.call_function(func, tags)

    def del_func_str(self, func_name, str_mess):
        list_str_cmd = config.cmds_void[func_name]["word_list"]
        self.error_correction(str_mess, list_str_cmd)
        for str_cmd in list_str_cmd:
            if str_cmd in str_mess:
                data_key = str_mess.replace(str_cmd, "")
                return data_key[1 : len(data_key)]


class Cheek_Queue:
    def __init__(self, stop="", stop_flag=True):
        self.stop = stop
        self.stop_flag = stop_flag

    def set_Queue(self, stop_sr) -> None:
        self.stop_sr = stop_sr

    def cheek_Queue(self):
        if not self.stop_sr.empty():
            self.stop = self.stop_sr.get()
        elif self.stop_sr.empty():
            pass
        if self.stop == "True" and not self.stop_flag:
            self.stop_flag = True
            return None
        if self.stop == "True" and self.stop_flag:
            return self.stop_flag
        elif self.stop == "False":
            self.stop_flag = False
            return self.stop_flag

    def iterator(self, iter_now, len_data, iter_step):
        if len_data == iter_step:
            iter_now = 0
            # iter_now=0
        elif iter_now >= len_data:
            if iter_step > 0:
                iter_now = len_data - iter_step
            elif iter_step < 0:
                iter_now = len_data + iter_step
            if iter_now < 0:
                iter_now = 0
                iter_step = len_data
        elif (iter_now + iter_step) >= len_data and iter_step > 0:
            if len_data >= iter_now:
                temp = len_data - iter_now
                if temp != 0 and iter_step > temp:
                    iter_step = temp
                    print(temp)
                    # iter_now+=iter_step

        elif iter_now <= 0:
            iter_now = 0
        elif (iter_now + iter_step) < 0 and iter_step < 0:
            iter_now = 0
        else:
            pass
        if len_data < abs(iter_step):
            iter_step = len_data
        return iter_now, abs(iter_step)


class Error_log:
    def __init__(self) -> None:
        pass

    def set_error(self, error):
        print(error)
